package com.gmrz.uaf.remote.protocol.v1.processor;

import com.gmrz.service.challengestore.ChallengeStoreException;
import com.gmrz.service.challengestore.ChallengeStoreService;
import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.common.UAFException;
import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
import com.gmrz.uaf.protocol.v1.schema.OOBInfo;
import com.google.gson.Gson;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class UAPOOBStatusProcessor {
    private static final Logger LOG = LogManager.getLogger(UAPOOBStatusProcessor.class);

    /**
     * @param authToken
     * @return
     * @throws UAFException
     */
    public OOBInfo oobStatus(String authToken) throws UAFException {
        OOBInfo oobInfo = null;
        try {
            // 根据认证令牌去缓存中查询
            oobInfo = this.getCacheOOBInfo(authToken);
            if (null != oobInfo) {
                if (oobInfo.getStatus() == Constants.OOBStatus.APP_AUTH.getStatus() ||
                        oobInfo.getStatus() == Constants.OOBStatus.SERVER_AUTH.getStatus() ||
                        oobInfo.getStatus() == Constants.OOBStatus.AUTH_FAIL.getStatus()) {
                    //this.removeCacheOOBInfo(authToken);
                }
            }
        } catch (Exception e) {
            LOG.error("oobGenerate error", e);
            throw new UAFException(UAFErrorCode.PROTOCOL_OOB_STATUS_ERROR);
        }
        if (null != oobInfo) {
            return oobInfo;
        } else {
            throw new UAFException(UAFErrorCode.PROTOCOL_AUTHTOKEN_NOT_FOUND);
        }
    }

    private OOBInfo getCacheOOBInfo(String key) throws ChallengeStoreException {
        Gson gson = new Gson();
        ChallengeStoreService mUafChallengeStoreService = GuiceUtil.getProcessorInjector().getInstance(ChallengeStoreService.class);
        String oobInfoStr = mUafChallengeStoreService.getRedisValue("uaf.oob." + key);
        if (com.gmrz.util.Strings.isNotBlank(oobInfoStr)) {
            return gson.fromJson(oobInfoStr, OOBInfo.class);
        } else {
            return null;
        }

    }

    private void removeCacheOOBInfo(String key) throws ChallengeStoreException {
        ChallengeStoreService mUafChallengeStoreService = GuiceUtil.getProcessorInjector().getInstance(ChallengeStoreService.class);
        mUafChallengeStoreService.deleteRedisValue("uaf.oob." + key);
    }
}
